
#import "MYShopBaseGoodSalesOrderVC.h"
#import "MYShopSalesOrderVC.h"
#import "MYShopGoodsInsuranceTestifyVC.h"
#import "YQAddressManageVC.h"
#import "YQPAddressModel.h"
#import "YQPCartListModel.h"
#import "MYShopSettlementModel.h"
#import "MYCreditsMallToOrderModel.h"

#import "MYShopCouponView.h"
@interface MYShopBaseGoodSalesOrderVC ()<YQAddressManagerVCDelegate>

@property (strong, nonatomic) YQPCouponModel *couponModel;

@end

@implementation MYShopBaseGoodSalesOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = kYQLS(@"确认订单");
}

-(void)setupView {
    [super setupView];
    self.isNavShadow = YES;
    kYQREGISTERTABLEVIEWNIBCELL(@"MYShopSalesOrderAddressCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"MYShopBaseGoodSalesOrderCell")
    //kYQREGISTERTABLEVIEWNIBCELL(@"MYShopCarCell")
    kYQREGISTERTABLEVIEWCELL([MYShopSalesOrderRemarkCell class])
    kYQREGISTERTABLEVIEWCELL([MYShopSalesOrderRightLbCell class])
    kYQREGISTERTABLEVIEWCELL([MYShopSalesOrderRightBtnCell class])
    kYQREGISTERTABLEVIEWCELL([MYShopSalesOrderInsuranceCell class])
    
    self.listTableView.backgroundColor = HexColor(0xFAFAFA);
    self.listTableView.frame = CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight-kHeight_Botton_SafeArea-49-Height_NavBar);
    //self.bottonView.frame = CGRectMake(0, kYQPScreenHeight-49, kYQPScreenWidth, 49);
    [self.view addSubview:self.bottonView];
    [self.bottonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-kHeight_Botton_SafeArea);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(49);
    }];
    
    if (!self.isIntegral) {
        #warning mark --测试
        self.postage = @"0.00";
        [self settlementAction];
    }

}

-(void)subOrderAction:(UIButton *)sender {
    
}

///结算获取默认地址，积分等信息 isIntegral
-(void)settlementAction {
    CGFloat totalGoodsAmount = 0.0;
    NSMutableArray *IdArr = [NSMutableArray array];
    
    NSMutableArray *skuArr = [NSMutableArray array];

    for (YQPCartModel *cartModel in self.selectGoodArray) {
        totalGoodsAmount += [cartModel.itemNumber integerValue] * [cartModel.price doubleValue];
        [IdArr addObject:cartModel.skuId];
        
        NSMutableDictionary *params = NSMutableDictionary.new;
        params[@"skuId"] = cartModel.skuId;
        params[@"skuNumber"] = cartModel.itemNumber;
        [skuArr addObject:params];
    }
    
    self.totalGoodsAmount = [NSString stringWithFormat:@"%.2lf",totalGoodsAmount];
    
    NSMutableDictionary *par = [NSMutableDictionary dictionary];
//    par[@"skuIds"] = [IdArr componentsJoinedByString:@","];
    par[@"skuSettlementList"] = skuArr;
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendPostRequest:kPOST_ORDER_SETTLEMENT_URL parameters:par success:^(YQPNetWorkingBaseModel *responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            self.settlementModel = [MYShopSettlementModel mj_objectWithKeyValues:responseObject.data];
            self.addresModel = self.settlementModel.userAddressEntity;
            self.settlementModel.couponHistory = 1.0;
            //self.settlementModel.discountAmount = 1.0;
            self.settlementModel.deliverMoney = 1.0;
            self.bottonView.priceLb.text = [NSString stringWithFormat:@"%@: ￥%@",kYQLS(@"总计"),self.payTotal];
            [self.listTableView reloadData];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
//        YQUITIPSERROR(error)
    }];
}

-(NSString *)payTotal {
    if (!self.totalGoodsAmount) {
        return @"";
    }
    CGFloat payTtoal = [self.totalGoodsAmount doubleValue];
    
    if (self.postage) {
        CGFloat postage = [self.postage doubleValue];
        payTtoal += postage;
    }
    
    if (self.couponModel.isSelect) {
        payTtoal -= self.couponModel.discountsAmount.doubleValue;
    }
    
    if (self.settlementModel.isIntegral) {
        payTtoal -= self.settlementModel.discountAmount;
    }
    
    if (self.settlementModel.isFreightInsurance) {
        payTtoal += self.settlementModel.deliverMoney;
    }
    
    return [NSString stringWithFormat:@"%.2lf",payTtoal];
}

-(void)setPostage:(NSString *)postage {
    _postage = [postage copy];
    [self.listTableView reloadData];
}

#pragma mark -- YQAddressManagerVCDelegate
- (void)selectAddressEntityModel:(YQPAddressEntityModel *_Nullable)model {
    self.addresModel = model;
    [self.listTableView reloadData];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return self.selectGoodArray.count + 1;
    }else if(section == 2) {
        return 2;
    }
    return 1;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (self.addresModel) {
            MYShopSalesOrderAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopSalesOrderAddressCell"];
            [cell setModel:self.addresModel];
            cell.rightBtn.userInteractionEnabled = NO;
            return cell;
        }else{
            YQTableViewBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kTableViewCell"];
            if (!cell){
                cell = [[YQTableViewBaseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"kTableViewCell"];
            }
            cell.contentView.backgroundColor = UIColor.whiteColor;
            cell.textLabel.text = kYQLS(@"添加收获地址");
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.textLabel.textColor = kAPPMainTitleColor;
            return cell;
        }
    }else if (indexPath.section == 1) {
        if (indexPath.row == self.selectGoodArray.count) {
            MYShopSalesOrderRemarkCell *remarkCell = [tableView dequeueReusableCellWithIdentifier:@"MYShopSalesOrderRemarkCell"];
            remarkCell.textLb.text = kYQLS(@"卖家留言");
            remarkCell.remarkTextField.text = self.message;
            ws(self);
            remarkCell.remarkTextBlock = ^(NSString * msg) {
                weakself.message = msg;
            };
            return remarkCell;
        }
        MYShopBaseGoodSalesOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopBaseGoodSalesOrderCell"];
        YQPCartModel *cartModel = nil;
        if (indexPath.row < self.selectGoodArray.count) {
            cartModel = self.selectGoodArray[indexPath.row];
        }
        cell.cartModel = cartModel;
        if (self.isIntegral) {
            cell.priceLb.text = [NSString stringWithFormat:@"￥%@ %@",cartModel.price,kYQLS(@"积分")];
        }else{
            cell.priceLb.text = [NSString stringWithFormat:@"￥%@",cartModel.price];
        }
        return cell;
    }else if (indexPath.section == 2) {
        if (indexPath.row == 0 || indexPath.row == 1) {
            MYShopSalesOrderRightLbCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopSalesOrderRightLbCell"];
            
            if (indexPath.row == 0) {
                cell.textLb.text = kYQLS(@"商品金额");
                cell.rightLb.textColor = kAPPThemeColor;
                cell.rightLb.text = @"$20.00";
                if (self.integralGoodsModel) {
                    cell.rightLb.text = [NSString stringWithFormat:@"%@ %@",self.integralGoodsModel.totalAmount,kYQLS(@"积分")];
                }
            }else{
                cell.textLb.text = kYQLS(@"邮费");
                cell.rightLb.textColor = HexColor(0xA0A0A0);
                cell.rightLb.text = @"$20.00";
                if (self.integralGoodsModel) {
                    cell.rightLb.text = [NSString stringWithFormat:@"%@",self.integralGoodsModel.freight];
                }
                
            }
            
            return cell;
        }
        else{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kTableViewCell"];
            if (!cell){
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"kTableViewCell"];
            }
            cell.contentView.backgroundColor = UIColor.lightGrayColor;
            return cell;
        }
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kTableViewCell"];
    if (!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"kTableViewCell"];
    }
    cell.contentView.backgroundColor = UIColor.lightGrayColor;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 83;
    }else if (indexPath.section == 1) {
        if (indexPath.row == self.selectGoodArray.count) {
            return 44;
        }
        return 124;
    }
    return 44;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
        YQAddressManageVC *addressVC = [[YQAddressManageVC alloc] init];
        addressVC.delegate = self;
        kYQPUSH(addressVC);
    }else if (indexPath.section == 2 && indexPath.row == 2){//优惠券列表弹框

    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 8;
    }
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end
#pragma makr -- lazy
-(MYShopSalesOrderBottonView *)bottonView {
    if (!_bottonView) {
        _bottonView = [MYShopSalesOrderBottonView viewFromXib];
        _bottonView.backgroundColor = UIColor.whiteColor;
        _bottonView.layer.shadowColor = HexColorA(0x000000, 0.6).CGColor;//RGB(70, 69, 69).CGColor;
        //2.设置阴影偏移范围
        _bottonView.layer.shadowOffset = CGSizeMake(0, 2);
        //3.设置阴影颜色的透明度
        _bottonView.layer.shadowOpacity = 0.5;
        
        //4.设置阴影半径
        _bottonView.layer.shadowRadius = 4;
        //5.设置阴影路径
        _bottonView.layer.shadowPath = [UIBezierPath bezierPathWithRect:_bottonView.bounds].CGPath;
        [_bottonView.subOrderBtn setTitle:kYQLS(@"提交订单") forState:(UIControlStateNormal)];
        [_bottonView.subOrderBtn addTarget:self action:@selector(subOrderAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
    }
    return _bottonView;
}
#pragma makr -- lazy end
@end
